import {
    login
} from '../../api/index'

const state = {
    token: sessionStorage.getItem('USER_TOKEN') != null ?
        sessionStorage.getItem('USER_TOKEN') : '',
    userInfo: sessionStorage.getItem('USER_INFO') != null ?
        sessionStorage.getItem('USER_INFO') : null,
}

const mutations = {
    SET_USER_TOKEN(state, token) {
        if (token) {
            state.token = token
            sessionStorage.setItem('USER_TOKEN', token)
        } else {
            state.token = ''
            sessionStorage.removeItem('USER_TOKEN')
        }
    },
    SET_USER_INFO(state, userInfo) {
        state.userInfo = userInfo
        sessionStorage.setItem('USER_INFO', userInfo)
    },
}


const actions = {
    setUserToken({
        commit
    }, token) {
        return new Promise((resolve) => {
            commit('SET_USER_TOKEN', token)
            resolve()
        })
    },
    async logout({
        commit
    }, msgFlag = false) {
        console.log('团四点八三接电话');
        sessionStorage.removeItem('USER_TOKEN')
        if (msgFlag) {
            message.success('注销成功', 0.5)
        }
        commit('SET_USER_TOKEN')
        window.location.reload()
        return Promise.resolve()
    },
    async login({
        commit
    }, data) {
        const response = await login(data)
        const {
            msg,
            code,
            data: {
                result: result
            },
        } = response
        const token = response.data.token
        if (token) {
            commit('SET_USER_TOKEN', token)
        }
        if (code === 200) {
            commit('SET_USER_INFO', JSON.stringify(result))
            return Promise.resolve({
                msg,
                result
            })
        } else {
            return Promise.reject(msg)
        }
    },
}

export default {
    namespaced: true,
    mutations,
    actions,
    state,
}